import { push as _push } from 'redux-first-history';
import { store } from "../store";
import printJs from 'print-js'

export const BASE_URL = () => {
  // return "https://yunxf.zje.com"; //线上
  if (process.env.CUSTOM_NODE_ENV === 'production') {
    return 'https://yunxf.zje.com' //线上
  } else if (process.env.CUSTOM_NODE_ENV === 'development') {
    return 'https://testyxf.zje.com' //测试
    // return 'https://yunxf.zje.com' //线上
  } else if (process.env.CUSTOM_NODE_ENV == 'safe') {
    return 'https://yunxfsafe.zje.com'
  }
}
export const formLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

export function formatMoney(text: number) {
  if (!text && text != 0) {
    return "-";
  } else {
    return "￥" + text.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
}

export function download(url: string, downloadName = "excel") {
  if (url && Object.prototype.toString.call(url) === "[object String]") {
    let a = document.createElement("a");
    a.href = encodeURI(url);
    a.download = downloadName;
    a.click();
  }
}

export function dispatchWithPromise(args: any) {
  return new Promise((resolve, reject) => {
    store.dispatch({ ...args, resolve, reject });
  });
}
export const tablePaginationConfig = {
  pageSizeOptions: ["10", "20", "30", "40", "50"],
  showTotal: (total: number, range: number[]) => {
    return `总共${total}条，当前第${range[0]}至${range[1]}条`;
  },
  showSizeChanger: true,
  showQuickJumper: true,
};
//乘法
export function accMul(arg1: number, arg2: number) {
  let m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) { }
  try {
    m += s2.split(".")[1].length;
  } catch (e) { }
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
}
export function htmlEncodeByRegExp(str: string) {
  var temp = "";
  if (str.length == 0) return "";
  temp = str.replace(/&/g, "&amp;");
  temp = temp.replace(/</g, "&lt;");
  temp = temp.replace(/>/g, "&gt;");
  temp = temp.replace(/\s/g, "%20");
  temp = temp.replace(/\'/g, "&#39;");
  temp = temp.replace(/\"/g, "&quot;");
  return temp;
}

export const getGlobalTableState = {
  loading: false,
  list: [],
  pageNum: 1,
  pageSize: 10,
  totalPage: 0,
  totalSize: 0,
};

export const uploadQiniuUrl: string = "https://upload.qiniup.com/";


export const push = (path: string) => {
  store.dispatch(_push(path));
}
//全屏
export function fullScreen() {
  let element: any = document.body;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
}

//页面自适应
export function setmultiple() {
  let innerWidth = window.innerWidth
  let innerHeight = window.innerHeight
  let radioWidth = innerWidth / 1920
  let radioHeight = innerHeight / 1080
  let multiple = radioHeight > radioWidth ? radioWidth : radioHeight
  document.body.style.setProperty('--multiple', String(multiple));
}

export const filterColumns = (data: [], key: string, type: 1 | 2 | 3) => {//type=1运营；type=2代理商；type=3开发商
  const state = store.getState();
  const userType = state.common.loginInfo.userType;
  if (type == userType) {
    return data.filter((item: any) => {
      return item.dataIndex != key
    })
  }

  return data;
}

//数组分裂
export const arrFlat = (arr: Array<any>, index: number) => {
  let newarr = []
  for (let i = 0; i < index; i++) {
    newarr[i] = arr
  }
  return newarr
}

/**
 * 下载文件
 * @param {*} data 对象
 * @param {*} fileName 文件名
 */
export const downLink = function (data: any, fileName: any) {
  const blob = new Blob([data], { type: "application/vnd.ms-excel" }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  const downloadElement = document.createElement("a");
  const href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  downloadElement.download = fileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放掉blob对象
}

/**
 * @function 其他购房人和子女的数组处理
 * @param {*} arr
 * @param {*} flag
 */
export const childArr = function (arr: any, flag: boolean = true) {
  console.log(arr)
  let newarr = JSON.parse(JSON.stringify(arr))
  if (newarr.length == 0) {
    return newarr
  }
  for (let i in newarr) {
    for (let j in newarr[i].quesVOList) {
      let item = newarr[i].quesVOList[j]
      if (item?.auditMsg) {
        let list = []
        try {

          list = JSON.parse(item?.auditMsg || '[]') || []
        } catch (err) {
        }
        let str = flag ? item.pid + '>>>' + item.url : item.pid + '>>>' + item.secondCat
        for (let listIndex in list) {
          if (list[listIndex][str]) {
            newarr[i].quesVOList[j].msg = list[listIndex][str]
          }
        }
        newarr[i].quesVOList[j].imgStatus = newarr[i].quesVOList[j].msg ? 1 : 0
      }
    }
  }
  return newarr
}
/**
 * @function flat 数组拉平
 * @param {} array
 */
export const flatten = function (array: any) {
  var flattend: any = [];
  (function flat(array) {
    array.forEach(function (el: any) {
      if (Array.isArray(el)) flat(el);
      else flattend.push(el);
    });
  })(array);
  return flattend;
}
/**
 * @function 自定义问题和查档编号和基础信息的数据处理
 * @param { Array } arr 数组
 */
export const ArrSetmsg = function (arr: any) {
  let newarr = JSON.parse(JSON.stringify(arr))
  newarr = newarr.map((item: any) => {
    let arr = []
    try {
      arr = JSON.parse(item?.auditMsg || '[]')
    } catch (err) {
    }
    for (let i = 0; i < arr.length; i++) {
      //身份证
      if (item.qkey == 'answerIdPhoto') {
        if (arr[i][item.secondCat]) {
          item.msg = arr[i][item.secondCat]
        }
      } else {
        if (arr[i][item.url]) {
          item.msg = arr[i][item.url]
        }
      }
      item.imgStatus = item.msg ? 1 : 0
      if (item.msg) {
        newarr.push({
          url: item.url,
          auditMsg: item.msg
        })
      }
    }
    return item
  })
  return newarr
}
/**
 * @function 数组对象转化成数组
 */
export const ArrayObjectToArray = function (arr: any) {
  let newarr = []
  for (let i in arr) {

    newarr.push(Object.values(arr[i])[0])
  }
  return newarr
}


/**
 * @function 获取传入参数的类型
 * @param {any} any 参数
 */
export const getObject = function (any: any) {
  const str = Object.prototype.toString.call(any).split(' ')[1]
  return str.substr(0, str.length - 1)
}

//获取年龄
export function getAge(idCard: string) {
  idCard = idCard + ''
  let oldyear = parseInt(idCard.substring(6, 10))
  let oldmonth = parseInt(idCard.substring(10, 12))
  let oldday = parseInt(idCard.substring(12, 14))
  let year = new Date().getFullYear()
  let month = new Date().getMonth() + 1
  let day = new Date().getDate()
  let age = year - oldyear
  if (month < oldmonth) {
    age = age - 1
  }
  if (month == oldmonth) {
    if (day < oldday) {
      age = age - 1
    }
  }
  return age + ''
}